import uuid

from django.core.validators import MaxValueValidator
from django.db import models
from django.db.models import SET_NULL
from django.utils import timezone

from apps.PaperManagement.models import Paper
from apps.DepartManagement.models import Department
from apps.UserManagement.models import User


class Exam(models.Model):
    class Meta:
        db_table = 'exam'

    objects = models.Manager()
    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255)
    # 绑定试卷ID
    paper = models.ForeignKey(Paper, null=True, max_length=255, on_delete=SET_NULL, related_name='exam', help_text='绑定试卷ID')
    # 考试名称
    title = models.CharField(max_length=100, help_text='考试名称')
    # 考试开始时间
    start_time = models.DateTimeField(verbose_name='考试开始时间')
    # 考试结束时间
    end_time = models.DateTimeField(verbose_name='考试结束时间')
    # 考试状态，0：未开始、1：进行中、2：已结束
    EXAM_STATUS_CHOICES = [
        (0, '未开始'),
        (1, '进行中'),
        (2, '已结束'),
        (3, '异常'),
    ]
    status = models.IntegerField(EXAM_STATUS_CHOICES, default=0, help_text='考试状态')
    # 考试次数，最高1000次
    number = models.IntegerField(default=0, help_text="考试次数", validators=[MaxValueValidator(1000)])

    re_answer = models.BooleanField(default=False, help_text='是否允许重做')
    show_answer = models.BooleanField(default=False, help_text='是否立即显示答案')
    # 父级考试
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, help_text='父级考试')
    # 创建时间
    created_at = models.DateTimeField(default=timezone.now, help_text='创建时间')
    # 更新时间
    updated_at = models.DateTimeField(auto_now=True, null=True, help_text='更新时间')


class ExamDepart(models.Model):
    """考试与部门关联表"""
    objects = models.Manager()
    exam = models.ForeignKey(Exam, on_delete=models.CASCADE, blank=True)
    depart = models.ForeignKey(Department, null=True, on_delete=SET_NULL, blank=True)
    user = models.ForeignKey(User, null=True, on_delete=SET_NULL, blank=True)
    # 创建时间
    created_at = models.DateTimeField(default=timezone.now, help_text='创建时间')
    # 更新时间
    updated_at = models.DateTimeField(auto_now=True, null=True, help_text='更新时间')

    class Meta:
        db_table = 'exam_depart_user'
        unique_together = ('exam', 'depart', 'user')
